<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>外线号码</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 搜索筛选 -->
    <el-form :inline="true" class="user-search">
      <el-form-item label="搜索：">
      </el-form-item>
      <el-form-item label="" v-for="(filter, index) in searchParams.filters" :key="index">
        <el-input size="small" v-model="filter.fieldValue" v-bind:fieldName="filter.fieldName" v-if="filter.showAble"
                  v-bind:fieldValue="filter.fieldValue" v-bind:compare="filter.compare" :disabled="filter.readonly"
                  @keyup.enter.native="search"
                  :placeholder="filter.placeholder" :readonly="filter.readonly" clearable/>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search()">搜索</el-button>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleAdd()">添加</el-button>
        <el-button size="small" type="primary" icon="el-icon-refresh" @click="handleSync()">同步</el-button>
      </el-form-item>
    </el-form>

    <!--列表-->
    <el-table size="small" :data="list" highlight-current-row v-loading="loading" border element-loading-text="拼命加载中"
              style="width: 100%;" :header-row-style="{width: '100%', color: 'darkorange'}">
      <el-table-column align="center" type="selection" width="60">
      </el-table-column>
      <el-table-column prop="pstnnumber" label="外线号码" width="120">
      </el-table-column>
      <el-table-column prop="nature.desc" label="码号性质" width="120">
      </el-table-column>
      <el-table-column prop="gateway" label="中继名称" width="100">
      </el-table-column>
      <el-table-column prop="line" label="并发数" width="100">
      </el-table-column>
      <el-table-column prop="areaCode" label="热线区号" width="150">
      </el-table-column>
      <el-table-column prop="createAt" label="创建时间" width="150">
      </el-table-column>
      <el-table-column prop="remark" label="备注" width="200">
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="200">
        <template slot-scope="scope">
          <el-dropdown trigger="click">
            <span class="el-dropdown-link">
              操作<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item :icon="'el-icon-edit'" @click.native="handleEdit(scope.$index, scope.row)">编辑
              </el-dropdown-item>
              <el-dropdown-item :icon="'el-icon-s-tools'" @click.native="allocationEdit(scope.$index, scope.row)">分配
              </el-dropdown-item>
              <el-dropdown-item :icon="'el-icon-user'" @click.native="handleToCompany(scope.$index, scope.row)">授权
              </el-dropdown-item>
              <el-dropdown-item :icon="'el-icon-refresh'" @click.native="changeNature(scope.$index, scope.row)">转换性质
              </el-dropdown-item>
              <el-dropdown-item :icon="'el-icon-delete-solid'" @click.native="deleteItem(scope.$index, scope.row)">删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination v-bind:child-msg="pageParams" @callFather="callFather"/>


    <!-- 新增界面 -->
    <el-dialog title="新增" :visible.sync="addFormVisible" width="50%" @click='closeDialog("edit")'>
      <el-form label-width="120px" :model="editForm" ref="editForm" :rules="rules">
        <el-form-item label="码号号码" prop="pstnnumber">
          <el-input size="small" type="number" v-model="editForm.pstnnumber" auto-complete="off" placeholder="请输入码号号码"/>
        </el-form-item>
        <el-form-item label="中继名称" prop="gateway">
          <el-input size="small" v-model="editForm.gateway" auto-complete="off" placeholder="请输入码号号码"/>
        </el-form-item>
        <el-form-item label="码号性质" prop="nature">
          <el-select style="width: 50%" v-model="editForm.nature" placeholder="请选择码号性质">
            <el-option :label="item.name" :value="item.value"
                       v-for="(item, index) in [{name: '共有', value: 0}, {name: '自有', value: 1}]"
                       :key="index"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click='closeDialog("edit")'>取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitAddForm('editForm')">保存
        </el-button>
      </div>
    </el-dialog>

    <!-- 编辑界面 -->
    <el-dialog title="编辑" :visible.sync="editFormVisible" width="50%" @click='closeDialog("edit")'>
      <el-form label-width="120px" :model="editForm" ref="editForm" :rules="rules">
        <el-form-item label="码号号码" prop="pstnnumber">
          <el-input size="small" :disabled="true" type="number" v-model="editForm.pstnnumber" auto-complete="off" placeholder="请输入码号号码"/>
        </el-form-item>
        <el-form-item label="中继名称" prop="gateway">
          <el-input size="small" :disabled="true" v-model="editForm.gateway" auto-complete="off" placeholder="请输入码号号码"/>
        </el-form-item>
        <el-form-item label="码号性质" prop="nature">
          <el-select style="width: 50%" :disabled="true" v-model="editForm.nature" placeholder="请选择码号性质">
            <el-option :label="item.name" :value="item.value"
                       v-for="(item, index) in [{name: '共有', value: 0}, {name: '自有', value: 1}]"
                       :key="index"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="并发数" prop="line">
          <el-input size="small" v-model="editForm.line" auto-complete="off" placeholder="请输入远端IP"/>
        </el-form-item>
        <el-form-item label="热线区号" prop="areaCode">
          <el-input size="small" v-model="editForm.areaCode" auto-complete="off" placeholder="请输入落地主叫改写规则"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click='closeDialog("edit")'>取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitAddForm('editForm')">保存
        </el-button>
      </div>
    </el-dialog>


    <!-- 分配界面 -->
    <el-dialog title="分配" :visible.sync="allocationVisible" width="50%" @click='closeDialog("edit")'>
      <el-form label-width="120px" :model="editForm" ref="editForm" :rules="rules">
        <el-form-item label="码号号码" prop="pstnnumber">
          <el-input size="small" :disabled="true" type="number" v-model="editForm.pstnnumber" auto-complete="off" placeholder="请输入码号号码"/>
        </el-form-item>
        <el-form-item label="中继名称" prop="gateway">
          <el-input size="small" :disabled="true" v-model="editForm.gateway" auto-complete="off" placeholder="请输入中继名称"/>
        </el-form-item>
        <el-form-item label="码号性质" prop="nature">
          <el-select style="width: 50%" v-model="editForm.nature" placeholder="请选择码号性质" :disabled="true">
            <el-option :label="item.name" :value="item.value"
                       v-for="(item, index) in [{name: '共有', value: 0}, {name: '自有', value: 1}]"
                       :key="index"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="并发数" prop="line">
          <el-input size="small" v-model="editForm.line" auto-complete="off" placeholder="请输入并发数"/>
        </el-form-item>
        <el-form-item label="企业编号" prop="companyNo">
          <el-input size="small" type="number" v-model="editForm.companyNo" auto-complete="off" placeholder="请输入企业编号"/>
        </el-form-item>
        <el-form-item label="热线区号" prop="areaCode">
          <el-input size="small" v-model="editForm.areaCode" auto-complete="off" placeholder="请输入热线区号"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click='closeDialog("edit")'>取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitAllocationForm('editForm')">保存
        </el-button>
      </div>
    </el-dialog>


    <!-- 授权弹窗 -->
    <el-dialog title="授权" :visible.sync="showConmanySelectDialog" width="70%" @click='closeDialog("perm")'>
      <el-form label-width="120px" :model="selectCompanyForm" ref="selectCompanyForm" :rules="selectCompanyFormRules">
        <el-form-item label="选择公司" prop="companyId">
          <el-select size="small" v-model="selectCompanyForm.companyId" placeholder="请选择" style="width: 80%">
            <el-option
              v-for="(item, index) in allCompany"
              :key="index"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
          <el-button size="small" type="primary" :loading="loading" class="title" @click="saveSelectCompanyForm">保存
          </el-button>
        </el-form-item>

      </el-form>

      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>已授权</span>
        </div>
        <!--列表-->
        <el-empty description="暂无授权信息" v-if="authList.length == 0"></el-empty>
        <el-table v-if="authList.length > 0" size="small" :data="authList" highlight-current-row v-loading="loading" border
                  element-loading-text="拼命加载中"
                  style="width: 100%;" :header-row-style="{width: '100%', color: 'darkorange'}">
          <el-table-column prop="number" label="外线号码">
          </el-table-column>
          <el-table-column prop="companyName" label="授权公司">
          </el-table-column>
          <el-table-column prop="createAt" label="授权时间">
          </el-table-column>
          <el-table-column align="center" label="操作" >
            <template slot-scope="scope">
              <el-button size="mini" type="danger" @click="handleDeleteAuth(scope.$index, scope.row)">回收</el-button>
            </template>
          </el-table-column>
        </el-table>
        <Pagination v-bind:child-msg="authPageParams" @callFather="callFather"/>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click='closeDialog("perm")'>取消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {
    numberCompanyDelete,
    numberCompanyList,
    pstnAdd,
    pstnAuth,
    pstnDelete,
    pstnEdit,
    pstnList,
    pstnSync,
    pstnAllocation
  } from "../../../api/baseMG";
  import Pagination from '../../../components/Pagination'
  import {deptAll} from "../../../api/userMG";
  import {getStore} from "../../../utils/util";

  export default {
    data() {
      var validRemoteIP = (rule, value, callback) => {
        if (this.editForm.nature && this.editForm.nature === "0") {
          if (!this.editForm.remoteIp) {
            return callback(new Error('共有码号需填写远端IP'));
          }
          let reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
          if (reg.test(value) === false) {
            callback(new Error("请输入正确格式IP如(11.11.11.11)"));
          }
        }
        callback();
      };
      var validSignalPort = (rule, value, callback) => {
        console.log(value);
        if (this.editForm.nature && this.editForm.nature === "0") {
          if (!value) {
            callback(new Error('共有码号需填写信令端口'));
          }
          if (value > 65535 || value < 0) {
            callback(new Error('信令端口不在可用区间'));
          }
        }
        callback();
      };
      return {
        list: [],
        authList: [],
        editFormVisible: false,
        addFormVisible: false,
        allocationVisible: false,
        showConmanySelectDialog: false,
        editTitle: "",
        allocationTitle: "分配",
        loading: false,
        editForm: {},
        selectCompanyForm: {},
        allCompany: [],
        rules: {
          pstnnumber: [
            {required: true, message: '请输入外呼号码', trigger: 'blur'}
          ],
          gateway: [
            {required: true, message: '请输入中继名称', trigger: 'blur'}
          ],
          nature: [
            {required: true, message: '请选择码号性质', trigger: 'blur'}
          ],
          remoteIp: [
            {validator: validRemoteIP}
          ],
          signalPort: [
            {validator: validSignalPort}
          ]
        },
        selectCompanyFormRules: {
          companyId: [
            {required: true, message: '请选择公司', trigger: 'blur'}
          ]
        },
        // 分页参数
        pageParams: {
          currentPage: 1,
          pageSize: 10,
          total: 10
        },
        authPageParams: {
          currentPage: 1,
          pageSize: 10,
          total: 10
        },
        searchParams: {
          page: 1,
          perPage: 10,
          filters: [
            {
              showAble: false,
              readonly: true,
              placeholder: "默认",
              fieldName: "belongUser",
              compare: "=",
              fieldValue: getStore("userInfo").userId
            },
            {
              showAble: true,
              readonly: false,
              placeholder: "请输入外呼号码",
              fieldName: "pstnnumber",
              compare: "like",
              fieldValue: ""
            }
          ],
          isLock: ''
        },
        searchAuthParams: {
          page: 1,
          perPage: 10,
          filters: [],
          isLock: ''
        }
      }
    },
    created() {
      this.search();
    },
    // 注册组件
    components: {
      Pagination
    },
    methods: {
      selectAllCompany() {
        deptAll().then(resp => {
          this.allCompany = resp.data;
        })
      },
      saveSelectCompanyForm() {
        this.$confirm('确定要授权吗?', '信息', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$refs['selectCompanyForm'].validate(valid => {
            if (valid) {
              pstnAuth(this.selectCompanyForm).then(resp => {
                if (resp.success) {
                  this.$message({
                    type: 'success',
                    message: resp.msg
                  });
                  this.search();
                } else {
                  this.$message({
                    type: 'error',
                    message: resp.msg
                  });
                }
                this.searchAuth(this.selectCompanyForm)
              })

            }
          });
        });
      },
      // 关闭编辑、增加弹出框
      closeDialog(dialog) {
        if (dialog === 'edit') {
          this.editFormVisible = false;
          this.addFormVisible = false;
          this.allocationVisible = false;
        } else if (dialog === 'perm') {
          this.showConmanySelectDialog = false
        } else if (dialog === 'unit') {
          this.unitAccessshow = false
        }
      },
      submitAddForm(params) {
        this.$refs[params].validate(valid => {
            if (valid) {
              if (!this.editForm.id) {
                pstnAdd(this.editForm).then(resp => {
                  if (resp.success) {
                    this.$message({
                      type: 'success',
                      message: resp.msg
                    });
                    this.addFormVisible = false;
                    this.editFormVisible = false;
                    this.search();
                  }
                })
              } else {
                pstnEdit(this.editForm).then(resp => {
                  if (resp.success) {
                    this.$message({
                      type: 'success',
                      message: resp.msg
                    });
                    this.editFormVisible = false;
                    this.addFormVisible = false;
                    this.search();
                  }
                })
              }
            }
          }
        );
      },
      submitAllocationForm(params) {
        this.$refs[params].validate(valid => {
            if (valid) {
              pstnAllocation(this.editForm).then(resp => {
                if (resp.success) {
                  this.$message({
                    type: 'success',
                    message: resp.msg
                  });
                  this.allocationVisible = false;
                  this.search();
                }
              })
            }
          }
        );
      },
      handleAdd() {
        this.editForm = {
          pstnnumber: "",
          remark: ""
        };
        this.addFormVisible = true
      },
      handleSync() {
        this.$confirm('同步外线号码仅新增系统不存在的码号信息，确定要同步外线号码信息吗?', '信息', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          pstnSync().then(resp => {
            if (resp.success) {
              this.$message({
                type: 'success',
                message: resp.msg
              });
            } else {
              this.$message({
                type: 'info',
                message: resp.msg
              })
            }
            this.search();
          })
        });
      },
      // 分页插件事件
      callFather(param) {
        this.searchParams.page = param.currentPage;
        this.searchParams.perPage = param.pageSize;
        this.getList(this.searchParams);
      },
      handleEdit(index, row) {
        this.editForm = {
          id: row.id,
          pstnnumber: row.pstnnumber,
          remark: row.remark,
          gateway: row.gateway,
          nature: row.nature.value
        };
        this.editFormVisible = true
      },
      allocationEdit(index, row) {
        this.editTitle = "分配";
        this.editForm = {
          id: row.id,
          pstnnumber: row.pstnnumber,
          remark: row.remark,
          gateway: row.gateway,
          nature: row.nature.value
        };
        this.allocationVisible = true
      },
      changeNature(index, row) {
        this.$confirm('您确定要转换外线号码性质吗?', '信息', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let nature = row.nature.value === 0 ? 1 : 0;
          let form = {id: row.id, nature: nature};
          pstnEdit(form).then(resp => {
            if (resp.success) {
              this.$message({
                type: 'success',
                message: resp.msg
              });
              this.editFormVisible = false;
              this.search();
            }
          })
        });
      },
      handleToCompany(index, row) {
        this.selectCompanyForm = {
          id: row.id,
          // companyId: row.companyId,
          pstnnumber: row.pstnnumber
        };
        this.selectAllCompany();
        this.searchAuth(row);
        this.showConmanySelectDialog = true;
      },
      search() {
        this.searchParams.currentPage = 1;
        this.getList(this.searchParams);
      },
      searchAuth(row) {
        this.searchAuthParams.filters = [];
        this.searchAuthParams.filters.push({
          showAble: false,
          readonly: true,
          placeholder: "默认",
          fieldName: "numberId",
          compare: "=",
          fieldValue: row.id
        });
        this.searchAuthParams.currentPage = 1;
        this.getAuthList(this.searchAuthParams);
      },
      getList(params) {
        pstnList(params).then(resp => {
          if (resp.success) {
            this.list = resp.data.list;
            this.pageParams.currentPage = resp.data.pageNum;
            this.pageParams.pageSize = resp.data.pageSize;
            this.pageParams.total = resp.data.total;
          }
        })
      },
      getAuthList(params) {
        numberCompanyList(params).then(resp => {
          if (resp.success) {
            this.authList = resp.data.list;
            this.authPageParams.currentPage = resp.data.pageNum;
            this.authPageParams.pageSize = resp.data.pageSize;
            this.authPageParams.total = resp.data.total;
          }
        })
      },
      handleDeleteAuth(index, row) {
        this.$confirm('确定要删除吗?', '信息', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          numberCompanyDelete(row.id).then(res => {
            if (res.success) {
              this.$message({
                type: 'success',
                message: res.msg
              });
              this.searchAuth({id: row.numberId})
            } else {
              this.$message({
                type: 'info',
                message: res.msg
              })
            }
          })
        })
      },
      deleteItem(index, row) {
        this.$confirm('确定要删除吗?', '信息', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          pstnDelete(row.id).then(res => {
            if (res.success) {
              this.$message({
                type: 'success',
                message: res.msg
              });
              this.search(this.formInline)
            } else {
              this.$message({
                type: 'info',
                message: res.msg
              })
            }
          })
            .catch(err => {
              this.loading = false;
              this.$message.error('删除失败，请稍后再试！')
            })
        })
          .catch(err => {
            console.error(err);
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
      }
    }
  }
</script>

<style scoped>
  .user-search {
    margin-top: 20px;
  }
</style>
